package com.zw.controller;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zw.entity.User;
import com.zw.service.UserService;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;
	
	@RequestMapping("/login.com")
	public String userLogin() {
		return "login";
	}
	@RequestMapping("/toAdd.com")
	public String userToken() {
		return "add";
	}
	@RequestMapping("/quit")
	public String quit(HttpSession session){
		session.removeAttribute("existUser");
		return "index";
	}
	@RequestMapping("/change")
	public String change(HttpSession session){
		session.removeAttribute("existUser");
		return "login";
	}
	
	@RequestMapping("/logining")
	public void logining(User user,HttpSession session,Boolean flag,HttpServletResponse res){
		System.out.println(flag);
		User existUser = userService.selectUserByUsernameAndPassword(user);
		System.out.println(existUser);
		if (null == existUser) {
			try {
				res.getWriter().write("failed");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else {
			if (null != flag) {
				Cookie cookie = new Cookie("existUser", existUser.getUser_name()+"#zw#"+existUser.getUser_password());
				cookie.setMaxAge(14*24*60*60);
				res.addCookie(cookie);
			}
			session.setAttribute("existUser", existUser);
			try {
				res.getWriter().write("settle");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	@RequestMapping("/add.do")
	public ModelAndView add(User user, HttpServletRequest req, HttpSession session) {
//		System.out.println(user.getUser_name());
		String ViewName = null;
		if (user.getUser_name() != "" && user.getUser_password() != null) {
			ViewName = "login";
			userService.addUser(user);
		} else {
			req.setAttribute("addUser", "注册失败");

		}

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(ViewName);
		return modelAndView;

	}

	
	

}
